<?php

namespace App\Http\Controllers\Api;

use App\Repositories\Admin\HistoryRepository;
use App\Repositories\Admin\RankRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\Admin\PictureRepository;
use Illuminate\Support\Facades\Redis;
use App\Repositories\Admin\UserRepository;

class MatchController extends Controller
{
    protected $pictureRepository;
    protected $historyRepository;
    protected $userRepository;
    protected $rankRepository;
    public function __construct(PictureRepository $pictureRepository)
    {
        $historyRepository = new HistoryRepository();
	$userRepository = new UserRepository();
        $rankRepository = new RankRepository();
        $this->historyRepository = $historyRepository;
        $this->pictureRepository = $pictureRepository;
        $this->rankRepository = $rankRepository;
	$this->userRepository = $userRepository;
    }
    public function getPictrue(Request $request){
        $oppenId = $request->get('oppenId');
        $userId = $request->get('userId');
        $pictureType = $request->get('pictureType');


        if(!Redis::get($oppenId)) {
            $pictures = $this->getPictureFromDB($userId,$oppenId,$pictureType);
            return json_encode(['code' => 200, 'pictures' => $pictures]);
        }else{
            $history = Redis::get($oppenId);
            $ids = unserialize($history);
            $pictures = [];
            if(count($ids) < 4){
                $pictures = $this->getPictureFromDB($userId,$oppenId,$pictureType);
            }else {
                $keys = array_rand($ids, 2);
                $twoIds = [];
                $twoIds[] = $ids[$keys[0]];
                $twoIds[] = $ids[$keys[1]];
                unset($ids[$keys[0]]);
                unset($ids[$keys[1]]);
                Redis::set($oppenId, serialize($ids));
                $pictures = $this->pictureRepository->getMatchPicture($twoIds);
            }
            return json_encode(['code' => 200, 'pictures' => $pictures,'ids'=>$ids]);
        }

    }
    public function getPictureFromDB($userId,$oppenId,$pictureType){
        //获取图片库里的所有图片id
        $pictures = $this->pictureRepository->getMatchAll($pictureType)->toArray();
        $pictureIds = array_column($pictures, 'picture_id');
        
	    //获取用户历史记录图片
        $histories = $this->historyRepository->getByUserId($userId)->toArray();
        $historyIds = array_merge(array_column($histories, 'history_picture_first_id'), array_column($histories, 'history_picture_second_id'));//两张图片的id

        $ids = array_diff($pictureIds, $historyIds); //可看图片id

        Redis::set($oppenId, serialize($ids));

	   if(count($ids)<2)  //可看图片少于两张则返回[]
            return [];

        $keys = array_rand($ids, 2);
        $twoIds = [];
        $twoIds[] = $ids[$keys[0]];
        $twoIds[] = $ids[$keys[1]];

        unset($ids[$keys[0]]);
        unset($ids[$keys[1]]);
        $pictures = $this->pictureRepository->getMatchPicture($twoIds);
        return $pictures;
    }

    /**
     * @param Request $request
     * @return string
     * 看图记录 升级
     */
    public function postPicture(Request $request){
        $user_id = $request->post('user_id');
        $choose_id = $request->post('choose_id');
        $pictures = $request->post('pictures');
        $userLike = [
            'history_user_id' => $user_id,
            'history_choosed_picture_id' => $choose_id,
            'history_picture_first_id' => $pictures[0],
            'history_picture_second_id' => $pictures[1],
        ];
        $likePicture = $this->pictureRepository->getById($choose_id);//获取被点赞的次数
        $likeNum = (int)$likePicture['picture_likenum'] + 1;
        $pictureResult = $this->pictureRepository->updateLikenum($choose_id,$likeNum) ;//添加图片的点赞记录


        $disLikeId = $pictures[0];  //获取没有被点的图片的id
        if($choose_id == $pictures[0])
            $disLikeId = $pictures[1];
        $disLikePicture = $this->pictureRepository->getById($disLikeId);   //获取没有被点赞的次数
        $disLikeNum = (int)$disLikePicture['picture_dislikenum'] + 1;
        $pictureResult = $this->pictureRepository->updateDislikenum($disLikeId,$disLikeNum) ;//添加图片的不赞记录

        $result = $this->historyRepository->createHistory($userLike);
	    //增加已用票数，减少总票数
        $addUsedTickeetNumber = 1;
        $user = $this->userRepository->getById($user_id);
        $usedTicket = $user['user_used_ticket'] + $addUsedTickeetNumber;//增加已用票
        $ticket = $user['user_ticket'] - $addUsedTickeetNumber;//减少可用票

        $usedTicketResult = $this->userRepository->updateUsedTicket($user_id,$usedTicket);//增加已用票数
        $newRank = $this->userUpgrade($user_id,$usedTicket);//检查并更新等级
        $TicketResult = $this->userRepository->updateTicket($user_id,$ticket);//减少可用票数
        return json_encode(['code'=>200,'history'=>$result->history_id,'usedTicket'=>$usedTicket,'ticket'=>$ticket,'newRank'=>$newRank]);
    }
    /**
     * 处理用户升级函数  百分比升级还未实现
     */
    public function userUpgrade($id,$usedTicket){
        $user = $this->userRepository->getById($id);
        $oldRankNumber = $user->user_rank_number;
        $newRankNumber = $oldRankNumber;
        $newRank = '';
        $userUprankTicket = '';
        for($i = $oldRankNumber;$i < 300; $i++) {
            $rank = $this->rankRepository->getByTypeRankNumberStatus(1, $i + 1, 1);
            if($rank != null ) {
                if ((int)$rank->rank_condition_type == 1) {
                    if ($usedTicket > $rank->rank_condition) {
                        $usedTicket = $usedTicket - $rank->rank_condition;
                        $usedTicketResult = $this->userRepository->updateUsedTicket($id,$usedTicket);//增加已用票数
                        $nextRank = $this->rankRepository->getByTypeRankNumberStatus(1, $i + 2, 1);
                        $userUprankTicket = $nextRank->rank_condition;
                        $userUprankTicketResult = $this->userRepository->updateUserUprankTicketNumber($id,$userUprankTicket);//修改下次升级票数
                        $newRank = $rank;
                        $newRankNumber = $rank->rank_number;
                    }
                } else if ($rank != null && (int)$rank->rank_condition_type == 2) { //百分比定等级
                    //
                }
            }
            $this->userRepository->updateUserRankNumber($id, $newRankNumber);
        }
        return ['rank'=>$newRank,'userUprankTicket'=>$userUprankTicket,'usedTicket'=>$usedTicket];
    }

    /**
     * 用户退出某组时删除用户的可看图的id缓存
     */
    public function clearUserMatchRdis(Request $request){
        $oppenId = $request->get('oppenId');
        if(Redis::get($oppenId)) {
            Redis::del($oppenId);
            return json_encode(['code'=>200,'msg'=>'删除成功','pictureIds'=>Redis::get($oppenId)]);
        }else
            return json_encode(['code'=>200,'msg'=>'没有数据可删除']);
    }

}
